package com.empire.module.member.service.dept;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.empire.module.member.dal.dataobject.user.DeptMemberDO;
import com.empire.module.member.dal.mysql.user.DeptMemberMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DeptMemberServiceImpl implements DeptMemberService {

    @Resource
    private DeptMemberMapper deptMemberMapper;

    @Override
    public Set<Long> getMemberDeptIds(Long memberId) {
        return deptMemberMapper.selectListByMemberId(memberId).stream().map(DeptMemberDO::getDeptId).collect(Collectors.toSet());
    }

    @Override
    public Long save(Long deptId, Long memberId, String updateUserId) {
        LambdaQueryWrapper<DeptMemberDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DeptMemberDO::getDeptId, deptId);
        queryWrapper.eq(DeptMemberDO::getMemberId, memberId).last(" limit 1");
        DeptMemberDO deptMemberDO = deptMemberMapper.selectOne(queryWrapper);
        if (deptMemberDO != null) {
            return deptMemberDO.getId();
        }
        DeptMemberDO deptMember = new DeptMemberDO();
        deptMember.setDeptId(deptId);
        deptMember.setMemberId(memberId);
        deptMember.setUpdater(updateUserId);
        deptMember.setCreator(updateUserId);
        int insert = deptMemberMapper.insert(deptMember);
        return insert > 0 ? deptMember.getId() : 0;
    }

    @Override
    public void deleteListByMemberId(Long memberId) {
        deptMemberMapper.deleteListByMemberId(memberId);
    }
}
